<?php

/**
 *
 * @author ben <ben@spicatech.cn>  Created on 2015-6-22
 */
class CustomSession {

    const KEY_PREFIX = 'custom_session_';
    const DEFAULT_EXPIRED = 300;

    private $keyPrefix = '';

    public function init() {
        $this->keyPrefix = self::KEY_PREFIX;
    }

    public function get($key) {
        if (!isset(Yii::app()->session[$this->keyPrefix . $key])) {
            return false;
        }
        $data = unserialize(Yii::app()->session[$this->keyPrefix . $key]);
        if (!is_array($data) || !isset($data['expired_time'])) {
            return false;
        }
        if ($data['expired_time'] < time()) {
            return false;
        }
        return $data['value'];
    }

    public function set($key, $value, $expired = self::DEFAULT_EXPIRED) {
        $data = array(
            'value' => $value,
            'expired_time' => strtotime("+{$expired} seconds")
        );

        Yii::app()->session[$this->keyPrefix . $key] = serialize($data);
    }

}
